const db = require('../db'); // mysql2/promise 实例

// 创建审批记录
async function createApproval(data) {
    const sql = `
    INSERT INTO approval
    (type, name, initiator, current_approver, approval_process, approval_log, approval_item, remark, attachment, status)
    VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
  `;
    const [result] = await db.execute(sql, [
        data.type,
        data.name,
        data.initiator,
        JSON.stringify(data.current_approver || []),
        JSON.stringify(data.approval_process || {}),
        JSON.stringify(data.approval_log || []),
        data.approval_item || null,
        data.remark || null,
        JSON.stringify(data.attachment || []),
        data.status ?? 1
    ]);
    return result.insertId;
}

// 获取所有审批
async function getAllApprovals() {
    const [rows] = await db.execute(`SELECT * FROM approval WHERE status != 2 ORDER BY created_at DESC`);
    return rows;
}

// 根据ID获取审批详情
async function getApprovalById(id) {
    const [rows] = await db.execute(`SELECT * FROM approval WHERE id = ?`, [id]);
    return rows[0] || null;
}

// 更新审批记录
async function updateApproval(id, data) {
    const sql = `
    UPDATE approval
    SET type = ?, name = ?, initiator = ?, current_approver = ?, approval_process = ?,
        approval_log = ?, approval_item = ?, remark = ?, attachment = ?, status = ?, ended_at = ?
    WHERE id = ?
  `;
    const [result] = await db.execute(sql, [
        data.type,
        data.name,
        data.initiator,
        JSON.stringify(data.current_approver || []),
        JSON.stringify(data.approval_process || {}),
        JSON.stringify(data.approval_log || []),
        data.approval_item || null,
        data.remark || null,
        JSON.stringify(data.attachment || []),
        data.status ?? 1,
        data.ended_at || null,
        id
    ]);
    return result.affectedRows > 0;
}

// 软删除审批记录
async function deleteApproval(id) {
    const [result] = await db.execute(`UPDATE approval SET status = 2 WHERE id = ?`, [id]);
    return result.affectedRows > 0;
}

module.exports = {
    createApproval,
    getAllApprovals,
    getApprovalById,
    updateApproval,
    deleteApproval
};
